package com.oncliedisk.administrator.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.oncliedisk.administrator.content.FileConfig;
import com.oncliedisk.administrator.content.OnlineConfig;
import com.oncliedisk.administrator.model.EntryModel;
import com.oncliedisk.administrator.model.FileTaskModel;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.VDiskAPI;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/12/3.
 */
public class Dao {
    private SqliteHelper helper;
    private static Dao dao;
    private SQLiteDatabase db;

    private Dao(Context context) {
        helper = new SqliteHelper(context);
        db = helper.getWritableDatabase();
    }

    public static Dao getInstance(Context context) {
        synchronized (Dao.class) {
            if (dao == null) {
                dao = new Dao(context);
            }
            return dao;
        }
    }


    /**
     * 获取所有目录
     *
     * @return
     */
    public List<EntryModel> getAllFile(String seleced, String[] str) {
        List<EntryModel> data = new ArrayList<EntryModel>();
        EntryModel model = null;
        //获取文件夹的所有第一层数据
        Cursor result = db.query("tb_file", null, seleced, str, null, null, "isDir Desc,mimeType Desc");
        if (result != null) {
            while (result.moveToNext()) {
                //如果有数据
                model = new EntryModel();
                //获取ID
                model.setId(result.getInt(result.getColumnIndex("_id")));
                //获取名字
                model.setFileName(result.getString(result.getColumnIndex("filename")));
                //获取文件字节数
                model.setBytes(result.getLong(result.getColumnIndex("bytes")));
                //获得Hash值
                model.setHash(result.getString(result.getColumnIndex("hash")));
                model.setIcon(result.getString(result.getColumnIndex("icon")));
                model.setIsDir(result.getInt(result.getColumnIndex("isDir")) == FileConfig.IS_DIR ? true : false);
                model.setModified(result.getString(result.getColumnIndex("modified")));
                model.setClientMtime(result.getString(result.getColumnIndex("clientMtime")));
                model.setPath(result.getString(result.getColumnIndex("path")));
                model.setRoot(result.getString(result.getColumnIndex("root")));
                model.setSize(result.getString(result.getColumnIndex("size")));
                model.setMimeType(result.getString(result.getColumnIndex("mimeType")));
                model.setMd5(result.getString(result.getColumnIndex("md5")));
                model.setSha1(result.getString(result.getColumnIndex("sha1")));
                model.setRevision(result.getString(result.getColumnIndex("revision")));
                model.setThumb(result.getString(result.getColumnIndex("thumb")));
                model.setRev(result.getString(result.getColumnIndex("rev")));
                model.setThumbExists(result.getInt(result.getColumnIndex("thumbExists")) == 1 ? true : false);
                model.setIsDeleted(result.getInt(result.getColumnIndex("isDeleted")) == 1 ? true : false);
                model.setIsFirst(result.getInt(result.getColumnIndex("isfirst")) == 1 ? true : false);
                model.setParent_url(result.getString(result.getColumnIndex("parent_url")));
                model.setDownPath(result.getString(result.getColumnIndex("downpath")));
                model.setLocalpath(result.getString(result.getColumnIndex("localpath")));
                data.add(model);
            }
        }
        return data;
    }

    /**
     * 更新指定对象的类型
     *
     * @param type
     * @param model
     */
    public void updateState(int type, String time, FileTaskModel model) {
        ContentValues values = new ContentValues();
        values.put("state", type);
        if (!TextUtils.isEmpty(time)) {
            values.put("date", time);
        }
        db.update("tb_task", values, "_id=?", new String[]{String.valueOf(model.getId())});
    }

    public void saveFileTask(FileTaskModel model) {
        ContentValues values = new ContentValues();
        values.put("filename", model.getFileName());
        values.put("size", model.getSize());
        values.put("progress", model.getProgress());
        values.put("state", model.getState());
        values.put("type", model.getType());
        values.put("path", model.getPath());
        values.put("shl", model.getShal());
        values.put("taskType", model.getTaskType());
        values.put("localPath", model.getLocalPath());
        long tb_task = db.insert("tb_task", null, values);
        Log.i("info", "插入一个数" + tb_task + "个数");
    }

    /**
     * 新建文件夹
     *
     * @param folderName 文件夹的名称
     * @param isFirst    //创建位置是否是在根目录
     * @param folder_id  //文件夹是隶属于哪个目录的ID下。
     */
    public void newFolder(String folderName, int isFirst, int folder_id) {
        ContentValues values = new ContentValues();
        values.put("name", folderName);
        values.put("date", new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(new Date(System.currentTimeMillis())).toString());
        values.put("isfirst", isFirst);
        values.put("folder_id", folder_id);
        db.insert("tb_folder", null, values);
        Log.i("info", "插入成功");
    }

    /**
     * 删除集合里的所有文件
     *
     * @param seleedModel
     */
    public void deleteModel(List<EntryModel> seleedModel) {
        //删除本地数据：
        for (EntryModel model : seleedModel) {
            db.delete("tb_file", "_id=?", new String[]{String.valueOf(model.getId())});
        }
    }

    /**
     * 删除下载删除功能
     *
     * @param seleedModel
     */
    public void deleteTask(FileTaskModel seleedModel) {
        //删除本地数据：
        db.delete("tb_task", "_id=?", new String[]{String.valueOf(seleedModel.getId())});
        File file = new File(OnlineConfig.DOWN_DIRECTORY + seleedModel.getFileName());
        if (file.exists()) {
            file.delete();
        }
        File file2 = new File(OnlineConfig.DOWN_DIRECTORY + seleedModel.getFileName() + OnlineConfig.DOWNLOAD_TEMP_FILE_SUFFIX);
        if (file2.exists()) {
            file2.delete();
        }
    }

    public void updateName(EntryModel model, String name) {
        ContentValues values = new ContentValues();
        values.put("filename", name);
        int update = db.update("tb_file", values, "_id=?", new String[]{String.valueOf(model.getId())});
    }

    /**
     * 更新数据
     *
     * @param id
     * @param map
     */
    public void updateData(int id, HashMap<String, String> map) {
        ContentValues values = new ContentValues();
        for (Map.Entry set : map.entrySet()) {
            values.put(String.valueOf(set.getKey()), String.valueOf(set.getValue()));
        }
        db.update("tb_task", values, "_id=?", new String[]{String.valueOf(id)});
    }

    /**
     * 根据传入的对象进行存储到数据库
     *
     * @param data
     * @param mApi
     * @return
     */
    public boolean saveFile(String deletePath, List<VDiskAPI.Entry> data, VDiskAPI<VDiskAuthSession> mApi) {
        //删除根目录的所有文件
        deleByParentPath(deletePath);
        ContentValues values = null;
        int success = 0;
        for (VDiskAPI.Entry entry : data) {
            //如果是文件
            values = new ContentValues();
            values.put("bytes", entry.bytes);
            values.put("hash", entry.hash);
            values.put("icon", entry.icon);
            values.put("isDir", entry.isDir);
            values.put("modified", entry.modified);
            values.put("clientMtime", entry.clientMtime);
            values.put("path", entry.path);
            values.put("root", entry.root);
            values.put("size", entry.size);
            values.put("mimeType", entry.isDir == true ? FileConfig.TYPE_FOLDER : entry.mimeType);
            values.put("md5", entry.md5);
            values.put("sha1", entry.sha1);
            values.put("revision", entry.revision);
            values.put("thumb", entry.thumb);
            values.put("rev", entry.rev);
            values.put("thumbExists", entry.thumbExists);
            values.put("isDeleted", entry.isDeleted);
            values.put("isfirst", entry.parentPath().equals("/") ? FileConfig.IS_FIRST : FileConfig.IS_OTHER);
            values.put("parent_url", entry.parentPath());
            values.put("filename", entry.fileName());
            db.insert("tb_file", null, values);
            success++;
        }
        if (success == data.size()) {
            return true;
        }
        return false;
    }


    /**
     * 根据路径，删除路径下所有数据
     *
     * @param path
     */
    private void deleByParentPath(String path) {
        if (!TextUtils.isEmpty(path)) {
            db.delete("tb_file", "parent_url=?", new String[]{path});
        }
    }


    public List<FileTaskModel> getTaskFileByType(String seleced, String[] parmes) {
        List<FileTaskModel> models = new ArrayList<FileTaskModel>();
        Cursor cursor = db.query("tb_task", null, seleced, parmes, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                FileTaskModel model = new FileTaskModel();
                model.setId(cursor.getInt(cursor.getColumnIndex("_id")));
                model.setState(cursor.getInt(cursor.getColumnIndex("state")));
                model.setSize(cursor.getString(cursor.getColumnIndex("size")));
                model.setTaskType(cursor.getString(cursor.getColumnIndex("taskType")));
                model.setShal(cursor.getString(cursor.getColumnIndex("shl")));
                model.setFileName(cursor.getString(cursor.getColumnIndex("filename")));
                model.setPath(cursor.getString(cursor.getColumnIndex("path")));
                model.setProgress(cursor.getString(cursor.getColumnIndex("progress")));
                model.setType(cursor.getString(cursor.getColumnIndex("type")));
                model.setDate(cursor.getString(cursor.getColumnIndex("date")));
                model.setLocalPath(cursor.getString(cursor.getColumnIndex("localPath")));
                model.setCurrSize(cursor.getString(cursor.getColumnIndex("currSize")));
                models.add(model);
            }
            return models;
        }
        return null;
    }

    /**
     * @param downloadURL
     * @param cachePath
     */
    public boolean updateDownPath(String downloadURL, String cachePath, int id) {
        ContentValues value = new ContentValues();
        value.put("downpath", downloadURL);
        value.put("localpath", cachePath);
        db.update("tb_file", value, "_id=?", new String[]{String.valueOf(id)});
        return true;
    }

    public void deleteStateByid(FileTaskModel model) {
        db.delete("tb_task", "_id=?", new String[]{String.valueOf(model.getId())});
    }

    public void deleteByName(String name) {
        db.delete("tb_task", "filename=? and state=?", new String[]{name, String.valueOf(FileTaskModel.STATE_DOWN_SUCCESS)});
    }

    public boolean  seleDownNumb(String currPath) {
        Cursor tb_file = db.query("tb_file", null, "parent_url=?", new String[]{currPath}, null, null, null);
        if(tb_file.moveToFirst() == false){
           return false;
        }
        return true;
    }
}
